<template>
  <div class="notification-component">
    <!-- 通知图标 -->
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
      <el-button
        type="text"
        :icon="Bell"
        @click="showNotificationDrawer = true"
        class="notification-btn"
      />
    </el-badge>

    <!-- 通知抽屉 -->
    <el-drawer
      v-model="showNotificationDrawer"
      title="消息通知"
      direction="rtl"
      size="400px"
    >
      <div class="notification-content">
        <!-- 通知操作栏 -->
        <div class="notification-actions">
          <el-button 
            type="text" 
            size="small" 
            @click="markAllAsRead"
            :disabled="unreadCount === 0"
          >
            全部已读
          </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="loadNotifications"
          >
            刷新
          </el-button>
        </div>

        <!-- 通知列表 -->
        <div class="notification-list">
          <div v-if="notifications.length === 0" class="empty-notifications">
            <el-empty description="暂无消息通知" />
          </div>
          
          <div 
            v-for="notification in notifications" 
            :key="notification.id" 
            class="notification-item"
            :class="{ 'unread': !notification.isRead }"
            @click="handleNotificationClick(notification)"
          >
            <div class="notification-avatar">
              <el-avatar :src="notification.senderAvatar" :size="40">
                {{ notification.senderName?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="notification-content">
              <div class="notification-header">
                <span class="sender-name">{{ notification.senderName }}</span>
                <span class="notification-time">{{ formatTime(notification.createdAt) }}</span>
              </div>
              <div class="notification-message">
                {{ getNotificationMessage(notification) }}
              </div>
              <div class="notification-target">
                {{ notification.targetTitle }}
              </div>
            </div>
            <div class="notification-status">
              <el-icon v-if="!notification.isRead" class="unread-dot" />
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <el-button 
            type="text" 
            @click="loadMoreNotifications"
            :loading="loading"
          >
            加载更多
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Bell } from '@element-plus/icons-vue'
import { getNotifications, markNotificationRead, getUnreadCount } from '@/api/blog'
import { useRouter } from 'vue-router'

const router = useRouter()

// 状态数据
const showNotificationDrawer = ref(false)
const notifications = ref([])
const unreadCount = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 20

// 获取通知列表
const loadNotifications = async (page = 1) => {
  try {
    loading.value = true
    const res = await getNotifications({ page, pageSize })
    
    if (res.success) {
      if (page === 1) {
        notifications.value = res.data.list || []
      } else {
        notifications.value.push(...(res.data.list || []))
      }
      
      hasMore.value = res.data.hasMore || false
      currentPage.value = page
    }
  } catch (error) {
    ElMessage.error('获取通知失败')
  } finally {
    loading.value = false
  }
}

// 加载更多通知
const loadMoreNotifications = () => {
  if (!hasMore.value || loading.value) return
  loadNotifications(currentPage.value + 1)
}

// 获取未读数量
const loadUnreadCount = async () => {
  try {
    const res = await getUnreadCount()
    if (res.success) {
      unreadCount.value = res.data.count || 0
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 标记所有已读
const markAllAsRead = async () => {
  try {
    const res = await markNotificationRead({ all: true })
    if (res.success) {
      notifications.value.forEach(item => {
        item.isRead = true
      })
      unreadCount.value = 0
      ElMessage.success('已全部标记为已读')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理通知点击
const handleNotificationClick = async (notification) => {
  // 标记为已读
  if (!notification.isRead) {
    try {
      await markNotificationRead({ notificationId: notification.id })
      notification.isRead = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }

  // 根据通知类型跳转到相应页面
  switch (notification.type) {
    case 'comment':
    case 'reply':
      // 跳转到博客详情页
      router.push(`/blog/${notification.targetId}`)
      break
    case 'like':
      // 跳转到博客详情页
      router.push(`/blog/${notification.targetId}`)
      break
    case 'follow':
      // 跳转到用户主页
      router.push(`/user/${notification.senderId}`)
      break
    default:
      break
  }

  // 关闭抽屉
  showNotificationDrawer.value = false
}

// 获取通知消息
const getNotificationMessage = (notification) => {
  switch (notification.type) {
    case 'comment':
      return '评论了你的博客'
    case 'reply':
      return '回复了你的评论'
    case 'like':
      return '点赞了你的博客'
    case 'follow':
      return '关注了你'
    case 'collect':
      return '收藏了你的博客'
    default:
      return notification.message || '发送了一条消息'
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

// 定时刷新未读数量
let refreshTimer = null

const startRefreshTimer = () => {
  refreshTimer = setInterval(() => {
    loadUnreadCount()
  }, 30000) // 每30秒刷新一次
}

const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(() => {
  loadUnreadCount()
  startRefreshTimer()
})

onUnmounted(() => {
  stopRefreshTimer()
})
</script>

<style scoped>
.notification-component {
  position: relative;
}

.notification-badge {
  margin-right: 10px;
}

.notification-btn {
  font-size: 18px;
  color: #666;
}

.notification-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-actions {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.notification-item:hover {
  background-color: #f8f9fa;
}

.notification-item.unread {
  background-color: #f0f8ff;
}

.notification-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.sender-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-message {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
  line-height: 1.4;
}

.notification-target {
  font-size: 12px;
  color: #999;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.notification-status {
  display: flex;
  align-items: flex-start;
  margin-left: 10px;
}

.unread-dot {
  width: 8px;
  height: 8px;
  background-color: #1890ff;
  border-radius: 50%;
  display: inline-block;
}

.empty-notifications {
  padding: 40px 0;
  text-align: center;
}

.load-more {
  text-align: center;
  padding: 15px 0;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-item {
    padding: 12px;
  }
  
  .notification-avatar {
    margin-right: 10px;
  }
  
  .sender-name {
    font-size: 13px;
  }
  
  .notification-message {
    font-size: 13px;
  }
}
</style> 